const Service = require('egg').Service;
const sd = require('silly-datetime')
const mkdirp = require('mkdirp')

const path = require('path')
const fs = require('fs')
const pump = require('pump')
module.exports = class UploadService extends Service {


    /**
     * 多文件上传
     */
    async uploadMore() {




    }
    /**
    * 多文件上传
    */
    async upload() {
        const { ctx } = this
        // 读取表单提交的文件流
        const stream = await ctx.getFileStream()
        const today = sd.format(new Date(), 'YYYYMMDD')
        const upload_dir = path.join(this.config.upload_path, today)

        await mkdirp(upload_dir)
        // 获取上传的文件名  like.jpg dog.png 
        const file_name = path.basename(stream.filename)

        // 拼接上传路径
        const upload_path = path.join(upload_dir, file_name)
        console.log(upload_path);
        // 创建一个可以写入的流
        const writeStream = fs.createWriteStream(upload_path)

        // 第一个参数读取流，第二个参数可写流, 上传失败会自动销毁流
        await pump(stream, writeStream)

        return {
            url:`${this.config.domainPath}/${today}/${file_name}`, // 上传路径
          
        }


    }



}